const express = require("express");
const app = express();

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*"); // 允许所有域访问
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT"); // 允许的HTTP方法
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  ); // 允许的头部字段
  next();
});

app.use("/sse", (req, res, next) => {
  let number = 0;
  const requestId = Date.now();
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");

  //自定义事件
  res.write(`event: start\n`)
  res.write(`data: hello world \n\n`);

  const intervalId = setInterval(() => {
    if (number > 9) {
      clearInterval(intervalId);
      res.end();
      return;
    }
    number++;
    const data = {
      message: `Num(${number}):This is a message from the server`,
      timestamp: Date.now(),
      requestId,
      finished: number === 10,
    };
    res.write(`data: ${JSON.stringify(data)}\n\n`);
  }, 2000);

  req.on("close", () => {
    console.log("--------- close connect --------");
    clearInterval(intervalId);
    res.end();
  });
});

app.listen(3001, () => {
  console.log("sever is starting!");
});
